package com.czy.daishusys.ui.bottom;

import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czy.daishusys.R;
import com.czy.daishusys.adapter.MessageFragmentAdapter;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.rxbus.RxBus;
import com.czy.daishusys.rxbus.Subscribe;
import com.czy.daishusys.rxbus.ThreadMode;
import com.czy.daishusys.ui.BaseFragment;
import com.czy.daishusys.ui.MainActivity;
import com.czy.daishusys.ui.message.ContactsFragment;
import com.czy.daishusys.ui.message.ConversationFragment;
import com.czy.daishusys.ui.message.MemberFrament;
import com.czy.daishusys.widget.CustomViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by yang on 2017/11/23.
 * 消息
 */

public class MessageFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_subtitle)
    TextView toolbarSubtitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.iv_message_tab_list)
    ImageView ivMessageTabList;
    @BindView(R.id.iv_message_tab_contacts)
    ImageView ivMessageTabContacts;
    @BindView(R.id.ll_message_hide)
    LinearLayout llMessageHide;
    @BindView(R.id.linear_content)
    LinearLayout linearContent;

    @BindView(R.id.tv_message_tab_list)
    TextView tvMessageTabList;
    @BindView(R.id.tv_message_tab_contacts)
    TextView tvMessageTabContacts;
    @BindView(R.id.tv_message_tab_cursor)
    TextView tvMessageTabCursor;
    //    @BindView(R.id.ll_tab_decoration)
//    LinearLayout llDecoration;
//    @BindView(R.id.appbar_message)
//    AppBarLayout appbarMessage;
    @BindView(R.id.viewpager_message_container)
    CustomViewPager mViewPager;
    Unbinder unbinder;
    private List<Fragment> fragments;
    private ConversationFragment conversationFragment;
    private ContactsFragment contactsFragment;
    private MessageFragmentAdapter mMessageFragmentAdapter;
    private int llDecorationHeight = -1, llMessageHideHeight = -1;
    private int cursorWidth, cursorOffset, cursorCurrent = 0;
    private TranslateAnimation mAnimation;
    private long decorationRefreshTime = 0;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_message;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        toolbarTitle.setText("消息");
//        appbarMessage.addOnOffsetChangedListener(this);

    }

    @Override
    protected void updateViews() {
        RxBus.getDefault().register(this);
        initTabs();
    }

    @Override
    public void onResume() {
        super.onResume();
        initCursor(cursorCurrent);
        setStatusBar();
    }

    public void initTabs() {
        fragments = new ArrayList<>();
        conversationFragment = new ConversationFragment();
        fragments.add(conversationFragment);
//        contactsFragment = new ContactsFragment();
//        fragments.add(contactsFragment);
        MemberFrament contactsFragment2 = new MemberFrament();
        fragments.add(contactsFragment2);
        mMessageFragmentAdapter = new MessageFragmentAdapter(getChildFragmentManager(), fragments);
        mViewPager.setAdapter(mMessageFragmentAdapter);
        mViewPager.addOnPageChangeListener(new MessagePagerListener());
        ivMessageTabList.setOnClickListener(new tabsOnClickListener(0));

        ivMessageTabContacts.setOnClickListener(new tabsOnClickListener(1));
        tvMessageTabList.setOnClickListener(new tabsOnClickListener(0));

        tvMessageTabContacts.setOnClickListener(new tabsOnClickListener(1));
        mViewPager.setPagingEnabled(false);
        mViewPager.setOffscreenPageLimit(2);

        //tabLayout.setupWithViewPager(mViewPager);
    }

//    @Override
//    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//        if (llDecorationHeight == -1 || llMessageHideHeight == -1) {
////            llDecorationHeight = llDecoration.getHeight();
////            llMessageHideHeight = llMessageHide.getHeight();
//        } else if (System.currentTimeMillis() - decorationRefreshTime >= 50) {
//            //MyLog.i(TAG, "onOffsetChanged:" + verticalOffset + "|" + llMessageHideHeight + "|" + llDecorationHeight);
////            ViewGroup.LayoutParams lp = llDecoration.getLayoutParams();
////            lp.height = (llMessageHideHeight - Math.abs(verticalOffset)) * llDecorationHeight / llMessageHideHeight;
////            llDecoration.setLayoutParams(lp);
//            decorationRefreshTime = System.currentTimeMillis();
//        }
//    }

    private class tabsOnClickListener implements View.OnClickListener {
        private int index;

        public tabsOnClickListener(int position) {
            index = position;
        }

        @Override
        public void onClick(View v) {

            if (index == cursorCurrent) return;
            tvMessageTabList.getPaint().setFakeBoldText(false);
            tvMessageTabContacts.getPaint().setFakeBoldText(false);
            changCursor(cursorCurrent, index);
            cursorCurrent = index;
            mViewPager.setCurrentItem(cursorCurrent);
        }
    }

    public class MessagePagerListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            changCursor(cursorCurrent, position);
            cursorCurrent = position;
            switch (position) {
                case 0:
                    toolbarTitle.setText("消息");
                    break;
                case 1:
                    toolbarTitle.setText("联系人");
                    break;


            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }


    private void initCursor(int cursorCurrent) {
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        // 获取分辨率宽度
        int screenW = dm.widthPixels;
        cursorOffset = screenW / 2;
        // 获取TextView宽度
        int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        linearContent.measure(width, height);
        cursorWidth = linearContent.getMeasuredWidth();
//        cursorOffset = (screenW / 3 - cursorWidth) / 2;// 计算偏移量
//        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) linearContent.getLayoutParams();
//        cursorWidth = layoutParams.width;
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tvMessageTabCursor.getLayoutParams();
        params.width = cursorWidth;

        // params.setMargins(dip2px(MainActivity.this, 1), 0, 0, 0); // 可以实现设置位置信息，如居左距离，其它类推
        // params.leftMargin = dip2px(MainActivity.this, 1);
        tvMessageTabCursor.setLayoutParams(params);
//        tvMessageTabCursor.measure(cursorOffset, height);
//        cursorWidth = tvMessageTabCursor.getMeasuredWidth();
//        cursorOffset = (screenW / 2 - cursorWidth) / 2;// 计算偏移量

        //初始化Cursor位置
        mAnimation = new TranslateAnimation(0, (cursorOffset - cursorWidth) / 2 + cursorOffset * cursorCurrent, 0, 0);
        mAnimation.setDuration(500);
        mAnimation.setFillAfter(true);
        tvMessageTabCursor.startAnimation(mAnimation);
    }

    private void changCursor(int fromCursor, int toCursor) {
        int fromXDelta = (cursorOffset - cursorWidth) / 2 + cursorOffset * cursorCurrent;
        int toXDelta = (cursorOffset - cursorWidth) / 2 + cursorOffset * cursorCurrent;
        mAnimation = new TranslateAnimation(fromXDelta, toXDelta, 0, 0);
        mAnimation.setDuration(500);
        mAnimation.setFillAfter(true);
        tvMessageTabCursor.startAnimation(mAnimation);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Subscribe(code = Constants.RXBUS_CODE_REFRESH_MESSAGE, threadMode = ThreadMode.MAIN)
    public void refresh(String event) {
        Log.i("King", "RXBUS_CODE_REFRESH_MESSAGE:");
        if (conversationFragment != null) {
            conversationFragment.refresh();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        RxBus.getDefault().unRegister(this);
    }


}
